package com.demo.htmltopng.service.impl;

import com.demo.htmltopng.util.ConvertToMultipartFile;
import com.demo.htmltopng.util.CustomWKHtmlToPdfUtil;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author AnYuan
 * 生成png服务实现
 */

@Slf4j
@Service
public class WkHtmlToxServiceImpl {

    @Resource
    private FreeMarkerConfigurer configuration;

    @Value("${wkhtmltox.path}")
    public String wkhtmltox_path;

    /**
     * Mock 数据
     * @return Map<String, String>
     */
    private Map<String, String> getUser() {

        String info = "<div class=\"qml-stem\"><p style=\"text-align: left;\"><span style=\"font-family: 宋体;\">为了探究某种植物种子萌发的最适条件，某生物兴趣小组将等量相同含水量的种子置于不同温度下进行萌发，实验时保持其它环境条件适宜且相同。记录</span><span style=\"font-family: 'Times New Roman';\">7</span><span style=\"font-family: 宋体;\">天后植物种子的萌发情况，结果如下表所示，根据表中数据得出的下列结论，正确的是（<span style=\"font-family: 'Times New Roman'\" qml-space-size=\"4\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>）</span></p><table style=\"border-width:0px 0px 0px 0px;border-style:solid;border-color:black;border-collapse: collapse;\"><tr  height=\"31px\"><td style=\"width:105px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 宋体;\">温度</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">5</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">10</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">15</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">20</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">25</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">30</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">35</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">40</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">45</span></p></td></tr><tr  height=\"31px\"><td style=\"width:105px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 宋体;\">种子萌发率</span><span style=\"font-family: 'Times New Roman';\">/%</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">9</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">18</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">36</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">68</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">91</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">86</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">73</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">29</span></p></td><td style=\"width:48px;vertical-align:center;border-width:1px 1px 1px 1px;border-style:solid solid solid solid;border-color:black;\"><p style=\"text-align: center;\"><span style=\"font-family: 'Times New Roman';\">16</span></p></td></tr></table><p style=\"text-align: left;\"><span></span></p><div class=\" qml-og\"><table class=\"qml-og\" style=\"width:100%\"><tr><td>A.&nbsp;<span class=\"qml-op\"><span style=\"font-family: 宋体;\">该实验设置的多组对照实验，实验变量分别是水、温度和种子的萌发率</span></span></td></tr><tr><td>B.&nbsp;<span class=\"qml-op\"><span style=\"font-family: 宋体;\">随着温度的上升，该植物种子的萌发率逐渐增高</span></span></td></tr><tr><td>C.&nbsp;<span class=\"qml-op\"><span style=\"font-family: 宋体;\">在环境温度为</span><span style=\"font-family: 'Times New Roman';\">25</span><span style=\"font-family: 宋体;\">℃时，该植物种子萌发率最高，此温度为种子萌发的最佳温度</span></span></td></tr><tr><td colspan=\"1\">D.&nbsp;<span class=\"qml-op\"><span style=\"font-family: 宋体;\">该实验数据表明，该植物种子的萌发率与种子含水量无关</span></span></td></tr></table></div></div>";

        Map<String, String> user = new HashMap<>(1);
        user.put("info", info);

        return user;
    }

    /**
     将html用画布转成图片
     @throws Exception e
     */
    public Map<String, Object> wkHtmlToPng() throws Exception {
        System.out.println("------------开始WKHtml转图片-----------------");
        Date start = new Date();

        Map<String, Object> dataR = new HashMap<>(3);

        // png图片宽度
        int width = 500;
        // png图片高度
        int height = 500;

        // 查询模版条件
        String templateCode = "T002";
        // 从项目resources目录读取一个模板（需要将com.demo.htmltopng.config.FreemarkerConfig配置文件干掉）
        // Template template = configuration.getConfiguration().getTemplate("jyeooTopic.html");
        // 从数据库查询一个模版
        Template template = configuration.getConfiguration().getTemplate(templateCode);

        // 将数据替换模版里面的参数
        String readyParsedTemplate = FreeMarkerTemplateUtils.processTemplateIntoString(template, getUser());

        ConvertToMultipartFile convertToMultipartFile = null;
        FileOutputStream fileOutputStream = null;
        File htmlFile = null;
        File imageFile = null;
        try {
            // 将html模板存入本地
            htmlFile = CustomWKHtmlToPdfUtil.toLocalHtmlFile(readyParsedTemplate);
            String absolutePath = htmlFile.getAbsolutePath();
            String path = System.getProperty("user.dir") + File.separator + "tmp" + File.separator + "wkhtmltopdf";
            String imagePath = path + File.separator + UUID.randomUUID() + ".png";
            imageFile = new File(imagePath);
            CustomWKHtmlToPdfUtil.run(absolutePath, imagePath, wkhtmltox_path);
            BufferedImage bi = ImageIO.read(imageFile);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", stream);

            width = bi.getWidth();
            height = bi.getHeight();

            byte[] imageByte = stream.toByteArray();
            fileOutputStream = new FileOutputStream(path + File.separator + "wkhtmltox.jpg");
            fileOutputStream.write(imageByte);

            convertToMultipartFile = new ConvertToMultipartFile(imageByte, "newNamepic", "pic1.jpg", "jpg", imageByte.length);
            Date end = new Date();
            long diff = (end.getTime() - start.getTime());
            System.out.println("总费时：" + diff + "毫秒");
            System.out.println("------------结束WKHtml转图片-----------------");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("HtmlToPng Exception", e);
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
           /* if (htmlFile != null) {
                htmlFile.deleteOnExit();
            }
            if (imageFile != null) {
                imageFile.deleteOnExit();
            }*/
        }
        dataR.put("file", convertToMultipartFile);
        dataR.put("width", width);
        dataR.put("height", height);
        return dataR;
    }

}
